<template>
  <div class="user-center-page">
    <header class="header"></header>
    <div class="pay-container">
      <div class="user">
        <div class="user-left">
          <img :src="imgUrl" class="user-avatar">
          <svg-icon iconClass="vip" class="icon-vip" v-if="userStatus!==1"/>
          <div class="user-info">
            <div class="email">{{ userInfo.Nickname }}</div>
            <span class="detail" v-if="userStatus===1">{{ $t('payment.nonMember') }}</span>
            <span class="valid" v-if="userStatus===2">{{ $t('payment.vaild') }} {{ expire }}</span>
            <span class="expires" v-if="userStatus===2">{{ $t('payment.expires',{day:day}) }}</span>
          </div>
        </div>
        <div class="exit" @click="exitLogin">{{ $t('payment.exit') }}</div>
      </div>
      <div v-if="userStatus!==3">
        <div class="pay-body">
          <div class="body-1" :class="{active:item.id===product.id}" v-for="(item,index) in productList" :key="index" :tabindex="index" @click="activeProduct(index,item.price)">
            <div class="month">{{ item|dayToI18n }}</div>
            <div class="device">{{5}} {{ $t('payment.device') }}</div>
            <div class="money">HK$<span class="number">{{ item.price|moneyToyuan }}</span></div>
            <div class="origin-money">HK${{ item.origin_price|valToFixed2 }}</div>
            <div class="day">{{ item|dayToMoney }}</div>
            <!-- <img :src="packageList.icon" alt="#" class="top" v-if="!index"> -->
            <svg-icon iconClass="top" class="top" v-if="!index"/>
          </div>
        </div>
        <div class="pay-content">
          <div class="pay-code">
            <HkWxPaymentCode
              v-if="isHkPay"
              ref="hkPayRef"
              :product="product"
              :hasLogin="hasLogin"
              :needAgree="!agreeChecked"
              :width="codeSize.width"
              :height="codeSize.height"
              :padding="codeSize.padding"
              :payLoading="payLoading"
              @onStatusChange="onStatusChange"
              @agree="agreeChecked = true"/>
          </div>
          <div class="pay-info">
            <ul class="pay-way">
              <li class="way-item"
                :class="{'active': activePayWay === way.id, 'loading': payLoading}"
                v-for="way in payWay"
                :key="way.id"
                @click="handleChangePayWay(way)">
                <p class="item-title">
                  <svg-icon :iconClass="way.iconClass" :size="20"></svg-icon>
                  <span>
                    {{ way.title }}
                  </span>
                </p>
                <div class="active-item"></div>
              </li>
            </ul>
            <p class="pay-amount">
              {{ $t('payment.pay') }}：
              <span class="amount-item">
                HK$<span class="amount-item-num">{{ payPrice }}</span>
              </span>
            </p>
            <div class="pay-agree">
              <el-checkbox v-model="agreeChecked">
                <a @click.prevent="openAgree" class="checkbox">{{ $t('payment.service') }}</a>
              </el-checkbox>
            </div>
          </div>
        </div>
      </div>
      <div class="vip" v-if="userStatus===3">
        <svg-icon iconClass="vip1" class="icon-vip1"/>
        <div class="forever">{{ $t('payment.forever') }}</div>
      </div>
      <el-dialog
        class="pay-dialog"
        :visible.sync="centerDialogVisible"
        :close-on-click-modal="false"
        center>
        <div v-if="payStatus=='checking'">
          <div class="limited">{{ $t('dialog.limited') }}</div>
          <div class="status"  v-loading="loading"  element-loading-spinner="el-icon-loading">{{ $t('dialog.check') }}</div>
          <div class="time">
            {{ minute }}
          </div>
        </div>
        <div v-else-if="payStatus=='expired'" class="timeout">
          <div>
            <svg-icon iconClass="error" class="icon"/>
          </div>
          <div class="success expired">{{ $t('dialog.again') }}</div>
        </div>
        <div v-else-if="payStatus=='success'" class="purchased">
          <div>
            <svg-icon iconClass="success" class="icon"/>
          </div>
          <div class="success">{{ $t('dialog.purchased') }}</div>
        </div>
      </el-dialog>
    </div>
  </div>

</template>
<script>
import { createOrder, pay, checkOrder } from '@/api/order'
import { getProducts } from '@/api/rights'
import { mapGetters } from 'vuex'
import { getLeftDay } from '@/utils/costum'
import i18n from '@/lang'
import HkWxPaymentCode from '@/components/payment-code/src/hk-wx-payment-code'

export default {
  name: 'UserCenterI18n',
  components: {
    HkWxPaymentCode
  },
  data () {
    return {
      agreeChecked: true,
      radio: '1',
      centerDialogVisible: false,
      payStatus: 'checking',
      loading: true,
      active: 0,
      orderId: '',
      sign: '',
      minute: '',
      productList: [],
      packageList: [],
      payPrice: 0,
      pkgId: null,
      userStatus: 1,
      expire: '',
      day: 0,
      payLoading: false,
      payWay: [
        {
          iconClass: 'wx',
          title: 'WeChat Pay',
          id: 'wx'
        },
        {
          id: 'paypal',
          iconClass: 'paypal',
          title: 'PayPal',
          payWay: 3
        },
        {
          id: 'stripe',
          iconClass: 'stripe',
          title: 'Stripe',
          payWay: 7
        }
      ],
      activePayWay: 'wx',
      codeSize: {
        width: 140,
        height: 140,
        padding: 5
      },
      selectedProduct: {}
    }
  },
  computed: {
    ...mapGetters(['appInfo', 'userInfo', 'appCfg', 'hasLogin']),
    product () {
      return this.productList[this.active] || {}
    },
    imgUrl () {
      return this.userInfo.Portrait || require('@/assets/user-avatar.png')
    },
    protocol () {
      if (i18n.locale === 'en') {
        return 'english'
      } else if (i18n.locale === 'zh') {
        return 'jtzw'
      } else {
        return 'ftzw'
      }
    },
    isHkPay () {
      return this.activePayWay === 'wx'
    }
  },
  watch: {
    centerDialogVisible (newVal) {
      if (!newVal) {
        clearInterval(this.timerId)
      }
    }
  },
  filters: {
    moneyToyuan (val = 0) {
      return parseFloat((val / 100).toFixed(2))
    },
    valToFixed2 (val = 0) {
      return (val / 100).toFixed(2)
    },
    dayToMoney (val = 0) {
      if (val.unlimited) {
        return i18n.t('payment.indefinitely')
      } else {
        const days = Math.round(val.bus_ext.duration / (24 * 60)) || 1
        return `HK$ ${(val.price / 100 / days).toFixed(2)} ${i18n.t('payment.perDay')}`
      }
    },
    dayToI18n (val) {
      if (val.unlimited) {
        return i18n.t('payment.indefinitely')
      } else {
        return i18n.t(`payment.${val.name}`)
      }
    }
  },
  created () {
    this.pkgId = this.appInfo.allPackages.length === 1 ? this.appInfo.allPackages.toString() : this.appInfo.allPackages
    this.$xz('xz_set_main_window_size', 720 + 24, 640 + 24)
    /** 获取在售权益包 */
    this.getPackages()
    this.getUser()
  },
  beforeDestroy () {
    clearInterval(this.timerId)
  },
  methods: {
    handleChangePayWay (way) {
      if (way.payWay) {
        if (this.payLoading) {
          return
        }

        this.payFunc(way.payWay)
        return
      }

      this.activePayWay = way.id
    },
    openAgree () {
      this.$xz('xz_open_url', `${this.appCfg.site}/vip-protocol-${this.protocol}.html`)
    },
    getUser () {
      if (!this.userInfo.user_id) {
        this.$store.dispatch('user/getUserInfo').then(() => {
          this.checkUserVip()
        })
      } else {
        this.checkUserVip()
      }
    },
    checkUserVip () {
      const buyPackage = this.userInfo.buy_right_package[0] || {}
      this.userStatus = 2
      if (buyPackage.unlimited) {
        this.userStatus = 3
      } else {
        const leftDay = getLeftDay(buyPackage.expire_at, this.userInfo.server_time)
        if (leftDay > 0) {
          this.expire = buyPackage.expire_at.split(' ')[0].replaceAll('-', '/')
          this.day = leftDay
          this.userStatus = 2
        } else {
          this.userStatus = 1
        }
      }
    },
    selectDay (Date_end) {
      const date1 = new Date(Date_end).getTime()
      // date2当前时间
      const date2 = new Date().getTime()
      const diff = date1 - date2 // 目标时间减去当前时间
      // 计算当前时间与结束时间之间相差天数
      return diff / (24 * 60 * 60 * 1000)
    },
    exitLogin () {
      this.$store.dispatch('user/logout').then(() => {
        this.$router.push({
          path: '/login-page',
          query: {
            type: 'emailLogin'
          }
        })
      }
      )
    },
    activeProduct (index, price) {
      this.active = index
      this.payPrice = parseFloat((price / 100).toFixed(2))
    },
    getPackages () {
      getProducts({ pkg_id: this.pkgId }).then(res => {
        this.productList = res.data.list || []
        this.payPrice = parseFloat((this.productList[0].price / 100).toFixed(2))
        if (res.data.package_list[0].rights) {
          res.data.package_list[0].rights.forEach(item => {
            if (item.right_id === '10001') { this.packageList = item }
          })
        }
      })
    },
    formatSeconds (value) {
      let theTime = parseInt(value)// 秒
      let middle = 0// 分
      if (theTime > 60) {
        middle = parseInt(theTime / 60)
        theTime = parseInt(theTime % 60)
        if (middle > 60) {
          middle = parseInt(middle % 60)
        }
      }
      this.minute = middle.toString().padStart(2, '0') + ':' + theTime.toString().padStart(2, '0')
    },
    setTime (type) {
      if (this.payStatus === 'checking' && this.centerDialogVisible) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          checkOrder({ orderid: this.orderId, type, sign: this.sign }).then(res => {
            const data = res.data
            if (data.status === 0) {
              this.onStatusChange()
            }
          }).finally(() => {
            this.setTime(type)
          })
        }, 3000)
      }
    },
    onStatusChange () {
      this.$store.dispatch('user/getUserInfo').then(() => {
        this.checkUserVip()
        this.payStatus = 'success'
        this.onPaySuccess()
      })
    },
    onPaySuccess () {
      this.$xz('xz_update_pay_result', true)
      this.$xzAsy('xz_get_stat_id').then(res => {
        if (/^8\d{3}$/.test(res) || !res) {
          const actionId = (res || 8002) + '9001'
          this.$xz('xz_substat_action', parseInt(actionId))
        } else {
          this.$xz('xz_substat_action', res)
        }
      })
      this.timerId && clearInterval(this.timerId)
      setTimeout(() => {
        this.centerDialogVisible = false
      }, 3000)
    },
    payFunc (payWay) {
      if (this.agreeChecked) {
        this.$refs.hkPayRef.cancelCheckOrder()
        this.payLoading = true
        const id = this.product.id
        const params = {
          product_id: [id],
          pay_way: payWay,
          pay_entry: 'web',
          channel_id: this.appInfo.channel
        }
        createOrder(params).then(res => {
          const data = res.data || {}
          this.orderId = data.order_id
          this.sign = data.sign

          const payWayStr = {
            3: 'paypal',
            7: 'stripe'
          }
          const params = {
            type: payWayStr[payWay],
            orderID: this.orderId,
            sign: this.sign,
            title: data.title,
            appID: process.env.VUE_APP_ID,
            project: process.env.VUE_APP_PROJECTID,
            callback: 'https://cleandesktop.kangaroooffice.com/',
            ...(payWay === 7 ? {
              payAppId: 'stripe1exzf4a451ba70a7'
            } : {})
          }
          pay(params).then(res => {
            this.payStatus = 'checking'
            this.centerDialogVisible = true
            this.payLoading = false
            const data = res.data || {}
            let time = data.expire
            // this.$xzAsy('xz_OpenPage', 'paypal', 600, 900, data.payURL)
            this.$xz('xz_open_url', data.payURL)
            this.timerId = setInterval(() => {
              this.formatSeconds(time)
              time--
              if (time < 0) {
                clearInterval(this.timerId)
                time = 0
                this.payStatus = 'expired'
                // this.$xz('xz_switch_dialog', 'paypal', false)
              }
            }, 1000)
            this.setTime(payWayStr[payWay])
          }).catch(() => {
            this.payLoading = false
          })
        }).catch(() => {
        })
      } else {
        this.$PsMessage({ message: this.$t('code.agree') })
      }
    }
  }
}

</script>
<style lang="scss" scoped>
.user-center-page{
  width: 100%;
  height: 100%;
}
.header{
  position: fixed;
  width: 1005px;
  top:0;
  height: 40px;
  background-color: #2D2E35;
  z-index: 99;
}
.user{
display: flex;
justify-content: space-between;
align-items: center;
height: 98px;
padding-bottom: 12px;
border-bottom:1px solid rgba(255, 255, 255, .1);
.user-left{
  position: relative;
  display: flex;
  align-items: center;
}
.user-avatar{
  position: relative;
  margin-right: 14px;
  width: 48px;
  height: 48px;
  border-radius: 50%;
}
.icon-vip{
  position: absolute;
  left: 29px;
  top: -5px;
  width: 24px;
  height: 24px;
}
.email{
  margin-bottom: 4px;
  font-size: 16px;
  font-weight: bold;
  color: #FFF;
}
.detail{
  font-size: 12px;
  color: rgba(255, 255, 255, .5);
}
.valid{
  font-size: 12px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 400;
  color: #F8DE9D;
}
.expires{
  margin-left: 22px;
  font-size: 12px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 400;
  color: #F65D5D;
}
.exit{
  font-size: 14px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 400;
  color: #FFF;
  cursor: pointer;

  &:hover {
    color: var(--color-primary-1);
  }
}
}
.pay-container{
  padding: 56px 45px 52px;
  .pay-body{
    margin-top: 38px;
    display: flex;
    column-gap: 10px;

    .body-1.active{
      border:1px solid #00BBD7;
      background: linear-gradient(359deg, rgba(0,187,215,0.2) 0%, rgba(0,187,215,0) 100%);
    }
    .body-1{
      position: relative;
      width: 150px;
      height: 185px;
      text-align: center;
      background: linear-gradient(359deg, #393939 0%, #545454 100%);
      border-radius: 10px;
      border: 1px solid rgba(255,255,255,0.2);
      outline:none;
      cursor: pointer;
      // &:focus{
      //   border:1px solid #00BBD7;
      //   background: linear-gradient(359deg, rgba(0,187,215,0.2) 0%, rgba(0,187,215,0) 100%);
      // }
      .month{
        margin: 16px 0 3px;
        font-size: 16px;
        font-weight: bold;
        font-family: Microsoft YaHei-Bold, Microsoft YaHei;
        color: #FFF;
      }
      .device{
        height: 16px;
        line-height: 16px;
        font-size: 14px;
        font-weight: 400;
        font-family: Arial-Regular, Arial;
        color: #00BBD7;
      }
      .money{
        margin: 18px 0 4px;
        margin-top: 18px;
        height: 30px;
        line-height: 30px;
        font-size: 26px;
        font-weight: bold;
        font-family: Arial-Regular, Arial;
        color: #FFF;
        .number{
          margin-left: 5px;
          font-family: Arial-Bold, Arial;
        }
      }
      .origin-money{
        margin-bottom: 18px;
        height: 18px;
        line-height: 18px;
        font-size: 16px;
        font-weight: 400;
        font-family: Arial-Regular, Arial;
        color: #FF4141;
        text-decoration: line-through;
      }
      .day{
        width: 100%;
        height: 41px;
        line-height: 41px;
        font-size: 14px;
        font-weight: 400;
        font-family: Arial-Regular, Arial;
        color: #F8DE9D;
        border-top: 1px solid rgba(255, 255, 255, 0.05);
      }
      .top{
        position: absolute;
        left: -16px;
        top: -13px;
        width: 40px;
        height: 40px;
      }
    }

  }

  .pay-content {
    display: flex;
    margin-top: 24px;
    column-gap: 30px;

    .pay-code {
      flex: none;
      width: 140px;
      height: 140px;
      background: #ddd;
    }

    .pay-info {
      display: flex;
      flex-flow: column nowrap;

      .pay-way {
        display: flex;
        flex-wrap: wrap;
        column-gap: 10px;
        row-gap: 10px;

        .way-item {
          position: relative;
          flex: none;
          width:  146px;
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 6px;
          background: #FFFFFF;
          overflow: hidden;
          cursor: pointer;
          box-sizing: border-box;

          &.active {
            box-shadow: 0 0 0 1px #00BBD7;

            .active-item {
              position: absolute;
              bottom: 0;
              right: 0;
              width: 0;
              height: 0;
              border: 13px solid transparent;
              border-color: transparent #00BBD7 #00BBD7 transparent;

              &::after {
                content: '';
                position: absolute;
                right: -10px;
                bottom: -8px;
                width: 8px;
                height: 5px;
                border: 1.5px solid #FFFFFF;
                border-color: transparent transparent #FFFFFF #FFFFFF;
                transform: rotate(-45deg);
              }
            }
          }

          &.loading {
            cursor: not-allowed;
          }

          .item-title {
            font-weight: 400;
            font-size: 12px;
            color: #000000;
            line-height: 14px;
            display: flex;
            align-items: center;
            column-gap: 6px;
          }
        }
      }

      .pay-amount {
        font-weight: 400;
        font-size: 14px;
        color: #FFFFFF;
        margin-top: 16px;
        display: flex;
        align-items: flex-end;

        .amount-item {
          color: #FF4141;
          line-height: 14px;

          .amount-item-num {
            font-weight: bold;
            font-size: 30px;
            margin-left: 4px;
            line-height: 30px;
          }
        }
      }

      .pay-agree {
        margin-top: 10px;

        /deep/ .el-checkbox__label {
          border-bottom: 1px solid rgba(255, 255, 255, .7);
          &:hover{
            color: var(--color-primary-1);
            border-bottom-color: var(--color-primary-1);
          }
        }
      }
    }
  }

  .el-checkbox{
    /deep/ .el-checkbox__inner{
      width: 14px;
      height: 14px;
      border-color: rgba(255,255,255,0.5);
      border-radius: 3px;
      &::after{
        border-color:var(--color-primary);
        top: 1px;
        left: 4px;
      }
    }

    /deep/ .el-checkbox__label{
      margin-left: 6px;
      padding: 0;
      font-size: 12px;
      font-weight: 400;
      font-family: Microsoft YaHei-Regular, Microsoft YaHei;
      color:rgba(255, 255, 255, .7);
    }
  }
  .pay-button{
    display: flex;
    justify-content: center;
    width: 100%;
    height: 50px;
    line-height: 50px;
    font-family: Microsoft YaHei-Bold, Micr;
    .button{
      width: 416px;
      font-size: 18px;
      font-weight: bold;
      color: #FFF;
      text-align: center;
      background: var(--color-primary);
      border-radius: 57px;
      border: none;
      &:hover{
        background-color: var(--color-primary-0);
      }
    }
  }
  .vip{
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    padding: 70px 0 107px;
    .icon-vip1{
      width: 190px;
      height: 190px;
    }
    .forever{
      margin-top: 40px;
      width: 100%;
      font-size: 20px;
      font-family: Microsoft YaHei-Bold, Microsoft YaHei;
      font-weight: bold;
      color: #F8DE9D;
      text-align: center;
    }
  }
  .pay-dialog{
    /deep/ .el-dialog{
      width: 310px;
      border-radius: 10px;
      box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.3);
      border: 1px solid rgba(255,255,255,0.1);
      .el-dialog__header{
        padding: 0px;
        .el-dialog__headerbtn{
          top:16px;
          right: 16px;
        }
      }
      .el-dialog__body{
        padding: 0 25px;
        .limited{
          display: flex;
          justify-content: center;
          margin-top: 40px;
          font-size: 16px;
          font-weight: 400;
          color: #FFF;
          // text-align: left;
          font-family: Arial-Regular, Arial;
          }
        .status{
          margin: 13px 0 11px;
          font-size: 14px;
          font-weight: 400;
          text-align: center;
          color: var(--color-primary-1);
          font-family: Arial-Regular, Arial;
          .el-loading-mask{
            top:21px;
            right:191px;
            background-color: transparent;
          }
        }
        .time{
          margin-bottom: 36px;
          font-size: 14px;
          font-weight: 400;
          color: #FF4141;
          text-align: center;
          font-family: Arial-Regular, Arial;
        }
        .success{
          margin-top: 10px;
          font-size: 16px;
          font-weight: 400;
          color: #FFF;
          font-family: Microsoft YaHei-Regular, Microsoft YaHei;
        }
        .expired{
          text-align: initial;
          display: flex;
          justify-content: center;
          // text-align: left;
        }
        .icon{
          width: 30px;
          height: 30px;
        }
        .timeout{
          margin: 44px 20px;
          text-align: center;
        }
        .purchased{
          margin: 54px 0;
          text-align: center;
        }
        .error{
          margin-top: 32px;
          text-align: center;
          .refresh{
            margin: 17px 0 30px;
            padding: 0;
            width: 140px;
            height: 32px;
            line-height: 32px;
            background-color: var(--color-primary);
            border-radius: 5px;
            border: none;
            &:hover{
              background-color: var(--color-primary-0);
            }
          }
        }
      }
    }
  }
}
</style>
